import { Component, game, Label, Sprite, _decorator } from "cc";
import { GlobalConfig } from "../../GlobalConfig";
import { Loger } from "../loger/Loger";
import SpriteUtils from "../utils/SpriteUtils";
import HotUpdate, { HotOptions } from "./HotUpdate";
import { HotUpdateEvent } from "./HotUpdateEvent";
import { HotUpdateInfo } from "./HotUpdateInfo";

/**
 * 热更新组件
 */
const { ccclass, property, menu } = _decorator;

@ccclass
@menu("FrameWork/ComHotUpdate")
export default class ComHotUpdate extends Component {
    @property({ displayName: '热更新进度条', type: Sprite })
    updateProgress: Sprite = null;

    @property({ displayName: '消息提示', type: Label })
    tipsLabel: Label = null;
    @property({ displayName: '进度条百分比', type: Label })
    txtProg: Label = null;
    @property({ displayName: '热更资源版本号', type: Label })
    txtResVersion: Label = null;
    private static _instance: ComHotUpdate;
    public static getInstance(): ComHotUpdate {
        if (!this._instance) {
            Loger.error("========ComHotUpdate 还未初始化===========")
            return null;
        }
        return this._instance;
    }
    
    onLoad() {
        ComHotUpdate._instance = this;
        this._initView();
    }

    onDestroy(){
        ComHotUpdate._instance = null;
    }

    _initView() {
        this.tipsLabel.string = '';
        // this.versionLabel.string = '';
        this.updateProgress.fillRange = 0.1;
        // this.addNode.destroyAllChildren();

        this.txtResVersion.node.active = false;
        this.txtResVersion.string = ``;
    }

    checkVersion(hotInfo: HotUpdateInfo) {
        if (GlobalConfig.closeHotUpdate) {
            Loger.log("G_Config.closeHotUpdate")
            HotUpdateEvent.ON_HOT_UPDATE_DONE.emit();
            return;
        }

        if (hotInfo) {
            Loger.log("===服务器返回的版本检查数据：", JSON.stringify(hotInfo));
            if (hotInfo.force) {
                //大版本更新
                HotUpdateEvent.ON_NEW_APP_VERSION.emit(hotInfo);
                // cc.sys.openURL(data.DownUrl);
                // let verInfo: VersionInfo = {
                //     desc: data.desc || "版本更新",
                //     downloadUrl: data.DownUrl,
                //     force: 1
                // };
                // ViewMgr.getInstance().showView(new VMVersionCheck(verInfo, null));
            } else {
                /**需要热更新 */
                // this.txtResVersion.node.active = Boot.debug;
                // this.txtResVersion.string = `ResVersion:${Boot.hotVersion}`;
                let options = new HotOptions();
                options.OnVersionInfo = (data) => {
                    let { local, server } = data;
                    // this.versionLabel.string = `本地版本号:${local}, 服务器版本号:${server}`;
                };
                options.OnUpdateProgress = (event: jsb.EventAssetsManager) => {
                    let bytes = event.getDownloadedBytes() + '/' + event.getTotalBytes();
                    let files = event.getDownloadedFiles() + '/' + event.getTotalFiles();

                    let file = event.getTotalFiles() > 0 ? event.getPercentByFile() : 0;
                    let byte = event.getTotalBytes() > 0 ? event.getPercent() : file;
                    let msg = event.getMessage();

                    Loger.log('[update]: 进度=' + byte);
                    // this.updateProgress.progress = parseFloat(file);
                    SpriteUtils.spriteFiledUpTo(this.updateProgress, byte)
                    this.txtProg.string = `${(byte * 100).toFixed(0)}%`;
                    this.tipsLabel.string = '正在加载资源,请耐心等待';
                    this.txtResVersion.string = "更新中";
                    Loger.log(msg);
                };
                options.OnNeedToUpdate = (data) => {
                    Loger.log("===检测到新版本,点击确定开始更新")
                    this.txtResVersion.string = "检测到新版本";
                    HotUpdate.hotUpdate();
                };
                options.OnNoNeedToUpdate = () => {
                    Loger.log("===不需要更新")
                    // this.txtResVersion.string = `ResVersion:${Boot.hotVersion}`;
                    HotUpdateEvent.ON_HOT_UPDATE_DONE.emit();
                };
                options.OnUpdateFailed = () => {
                    this.tipsLabel.string = '资源加载失败';
                    Loger.log("===更新失败")
                    this.txtResVersion.string = "更新失败";
                    HotUpdate.checkUpdate();

                };
                options.OnUpdateSucceed = () => {
                    this.tipsLabel.string = '资源加载成功';
                    Loger.log("===更新成功,重启游戏")
                    this.txtResVersion.string = "更新成功,重启游戏";
                    this.updateProgress.fillRange = 1;
                    
                    // audioEngine.stopAll();
                    game.restart();
                };
                HotUpdate.checkVersion(options, hotInfo);
            }
        }
    }

}
